using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;

namespace GameSystems
{
    /// <summary>
    /// UI主题系统 - 管理应用的主题切换和样式
    /// </summary>
    public class UIThemeSystem : MonoBehaviour
    {
        #region Enums

        /// <summary>
        /// 主题类型
        /// </summary>
        public enum ThemeType
        {
            Light,
            Dark,
            Custom
        }

        #endregion

        #region Data Classes

        /// <summary>
        /// 主题数据结构
        /// </summary>
        [Serializable]
        public class ThemeData
        {
            public string name;
            public ThemeType type;
            public Color primaryColor;
            public Color secondaryColor;
            public Color backgroundColor;
            public Color textColor;
            public Color accentColor;
            public Color buttonColor;
            public Color buttonTextColor;
            public Color inputFieldColor;
            public Color inputFieldTextColor;
            public Color panelColor;
            public Color borderColor;
            public Color shadowColor;
            public Color errorColor;
            public Color warningColor;
            public Color successColor;
            public Font primaryFont;
            public Font secondaryFont;
            public int fontSize;
            public float borderWidth;
            public float cornerRadius;
            public float shadowDistance;
            public Sprite backgroundImage;
            public Sprite buttonImage;
            public Sprite panelImage;
            public bool enableAnimations;
            public float animationSpeed;

            public ThemeData()
            {
                name = "Default";
                type = ThemeType.Light;
                primaryColor = Color.white;
                secondaryColor = Color.gray;
                backgroundColor = Color.white;
                textColor = Color.black;
                accentColor = Color.blue;
                buttonColor = Color.white;
                buttonTextColor = Color.black;
                inputFieldColor = Color.white;
                inputFieldTextColor = Color.black;
                panelColor = Color.white;
                borderColor = Color.gray;
                shadowColor = new Color(0, 0, 0, 0.3f);
                errorColor = Color.red;
                warningColor = Color.yellow;
                successColor = Color.green;
                fontSize = 14;
                borderWidth = 1f;
                cornerRadius = 5f;
                shadowDistance = 2f;
                enableAnimations = true;
                animationSpeed = 1f;
            }
        }

        #endregion

        #region Events

        /// <summary>
        /// 主题切换事件
        /// </summary>
        [Serializable] public class ThemeChangedEvent : UnityEvent<ThemeData> { }

        /// <summary>
        /// 主题加载完成事件
        /// </summary>
        [Serializable] public class ThemeLoadedEvent : UnityEvent<ThemeData> { }

        #endregion

        #region Serialized Fields

        [Header("主题配置")]
        [Tooltip("可用主题列表")]
        [SerializeField] private List<ThemeData> availableThemes = new List<ThemeData>();

        [Tooltip("默认主题索引")]
        [SerializeField] private int defaultThemeIndex = 0;

        [Tooltip("是否启用主题过渡动画")]
        [SerializeField] private bool enableTransitionAnimation = true;

        [Tooltip("主题过渡时间（秒）")]
        [SerializeField] private float transitionDuration = 0.5f;

        [Header("主题元素")]
        [Tooltip("应用主题的UI元素列表")]
        [SerializeField] private List<GameObject> themedElements = new List<GameObject>();

        [Tooltip("主题切换按钮")]
        [SerializeField] private Button themeToggleButton;

        [Tooltip("主题选择下拉菜单")]
        [SerializeField] private Dropdown themeDropdown;

        [Header("调试选项")]
        [Tooltip("是否启用调试日志")]
        [SerializeField] private bool enableDebugLogs = true;

        #endregion

        #region Events

        [Header("事件回调")]
        [Tooltip("主题切换时触发")]
        public ThemeChangedEvent OnThemeChanged;

        [Tooltip("主题加载完成时触发")]
        public ThemeLoadedEvent OnThemeLoaded;

        #endregion

        #region Private Fields

        private ThemeData currentTheme;
        private int currentThemeIndex = 0;
        private Dictionary<string, ThemeData> themeMap = new Dictionary<string, ThemeData>();
        private Dictionary<GameObject, Component[]> componentCache = new Dictionary<GameObject, Component[]>();
        private Coroutine transitionCoroutine;

        // 本地存储键
        private const string SavedThemeKey = "UIThemeSystem_SavedTheme";

        #endregion

        #region Unity Lifecycle

        /// <summary>
        /// 初始化组件
        /// </summary>
        private void Awake()
        {
            InitializeThemes();
            InitializeUI();
            CacheComponents();
        }

        /// <summary>
        /// 启动时的初始化
        /// </summary>
        private void Start()
        {
            LoadSavedTheme();
            ApplyTheme(currentTheme, false);
        }

        /// <summary>
        /// 清理资源
        /// </summary>
        private void OnDestroy()
        {
            CleanupCoroutines();
        }

        #endregion

        #region Public Methods

        /// <summary>
        /// 切换到指定主题
        /// </summary>
        /// <param name="themeName">主题名称</param>
        /// <param name="animate">是否使用动画</param>
        public void SwitchToTheme(string themeName, bool animate = true)
        {
            if (!themeMap.ContainsKey(themeName))
            {
                LogError($"主题 '{themeName}' 不存在");
                return;
            }

            var newTheme = themeMap[themeName];
            SwitchToTheme(newTheme, animate);
        }

        /// <summary>
        /// 切换到指定主题
        /// </summary>
        /// <param name="theme">主题数据</param>
        /// <param name="animate">是否使用动画</param>
        public void SwitchToTheme(ThemeData theme, bool animate = true)
        {
            if (theme == null)
            {
                LogError("主题数据为空");
                return;
            }

            if (currentTheme == theme)
            {
                LogDebug("已是当前主题，无需切换");
                return;
            }

            if (animate && enableTransitionAnimation)
            {
                StartThemeTransition(theme);
            }
            else
            {
                ApplyTheme(theme, false);
            }
        }

        /// <summary>
        /// 切换到下一个主题
        /// </summary>
        public void SwitchToNextTheme()
        {
            currentThemeIndex = (currentThemeIndex + 1) % availableThemes.Count;
            var nextTheme = availableThemes[currentThemeIndex];
            SwitchToTheme(nextTheme);
        }

        /// <summary>
        /// 切换到上一个主题
        /// </summary>
        public void SwitchToPreviousTheme()
        {
            currentThemeIndex = (currentThemeIndex - 1 + availableThemes.Count) % availableThemes.Count;
            var prevTheme = availableThemes[currentThemeIndex];
            SwitchToTheme(prevTheme);
        }

        /// <summary>
        /// 切换明暗主题
        /// </summary>
        public void ToggleLightDarkTheme()
        {
            if (currentTheme.type == ThemeType.Light)
            {
                // 切换到暗色主题
                var darkTheme = GetThemeByType(ThemeType.Dark);
                if (darkTheme != null)
                {
                    SwitchToTheme(darkTheme);
                }
            }
            else
            {
                // 切换到亮色主题
                var lightTheme = GetThemeByType(ThemeType.Light);
                if (lightTheme != null)
                {
                    SwitchToTheme(lightTheme);
                }
            }
        }

        /// <summary>
        /// 添加新主题
        /// </summary>
        /// <param name="theme">主题数据</param>
        public void AddTheme(ThemeData theme)
        {
            if (theme == null)
            {
                LogError("主题数据为空");
                return;
            }

            if (themeMap.ContainsKey(theme.name))
            {
                LogWarning($"主题 '{theme.name}' 已存在，将被替换");
            }

            availableThemes.Add(theme);
            themeMap[theme.name] = theme;

            // 更新下拉菜单
            UpdateThemeDropdown();

            LogDebug($"已添加主题: {theme.name}");
        }

        /// <summary>
        /// 移除主题
        /// </summary>
        /// <param name="themeName">主题名称</param>
        public void RemoveTheme(string themeName)
        {
            if (!themeMap.ContainsKey(themeName))
            {
                LogWarning($"主题 '{themeName}' 不存在");
                return;
            }

            var theme = themeMap[themeName];
            availableThemes.Remove(theme);
            themeMap.Remove(themeName);

            // 如果移除的是当前主题，切换到默认主题
            if (currentTheme == theme)
            {
                SwitchToTheme(availableThemes[defaultThemeIndex], false);
            }

            // 更新下拉菜单
            UpdateThemeDropdown();

            LogDebug($"已移除主题: {themeName}");
        }

        /// <summary>
        /// 获取主题
        /// </summary>
        /// <param name="themeName">主题名称</param>
        /// <returns>主题数据</returns>
        public ThemeData GetTheme(string themeName)
        {
            if (themeMap.ContainsKey(themeName))
            {
                return themeMap[themeName];
            }
            return null;
        }

        /// <summary>
        /// 获取当前主题
        /// </summary>
        /// <returns>当前主题数据</returns>
        public ThemeData GetCurrentTheme()
        {
            return currentTheme;
        }

        /// <summary>
        /// 获取所有可用主题
        /// </summary>
        /// <returns>主题列表</returns>
        public List<ThemeData> GetAvailableThemes()
        {
            return new List<ThemeData>(availableThemes);
        }

        /// <summary>
        /// 设置主题元素
        /// </summary>
        /// <param name="elements">主题元素列表</param>
        public void SetThemedElements(List<GameObject> elements)
        {
            themedElements = elements ?? new List<GameObject>();
            CacheComponents();

            // 重新应用当前主题
            if (currentTheme != null)
            {
                ApplyTheme(currentTheme, false);
            }
        }

        /// <summary>
        /// 添加主题元素
        /// </summary>
        /// <param name="element">主题元素</param>
        public void AddThemedElement(GameObject element)
        {
            if (element != null && !themedElements.Contains(element))
            {
                themedElements.Add(element);
                CacheComponent(element);

                // 应用当前主题到新元素
                if (currentTheme != null)
                {
                    ApplyThemeToElement(element, currentTheme);
                }
            }
        }

        /// <summary>
        /// 移除主题元素
        /// </summary>
        /// <param name="element">主题元素</param>
        public void RemoveThemedElement(GameObject element)
        {
            if (themedElements.Contains(element))
            {
                themedElements.Remove(element);

                if (componentCache.ContainsKey(element))
                {
                    componentCache.Remove(element);
                }
            }
        }

        /// <summary>
        /// 保存当前主题
        /// </summary>
        public void SaveCurrentTheme()
        {
            if (currentTheme != null)
            {
                PlayerPrefs.SetString(SavedThemeKey, currentTheme.name);
                PlayerPrefs.Save();
                LogDebug($"已保存主题: {currentTheme.name}");
            }
        }

        #endregion

        #region Private Methods

        /// <summary>
        /// 初始化主题
        /// </summary>
        private void InitializeThemes()
        {
            // 创建默认主题
            if (availableThemes.Count == 0)
            {
                CreateDefaultThemes();
            }

            // 构建主题映射
            themeMap.Clear();
            foreach (var theme in availableThemes)
            {
                themeMap[theme.name] = theme;
            }

            // 设置当前主题
            if (defaultThemeIndex >= 0 && defaultThemeIndex < availableThemes.Count)
            {
                currentTheme = availableThemes[defaultThemeIndex];
                currentThemeIndex = defaultThemeIndex;
            }
            else if (availableThemes.Count > 0)
            {
                currentTheme = availableThemes[0];
                currentThemeIndex = 0;
            }
        }

        /// <summary>
        /// 创建默认主题
        /// </summary>
        private void CreateDefaultThemes()
        {
            // 亮色主题
            var lightTheme = new ThemeData
            {
                name = "Light",
                type = ThemeType.Light,
                primaryColor = Color.white,
                secondaryColor = new Color(0.9f, 0.9f, 0.9f),
                backgroundColor = Color.white,
                textColor = Color.black,
                accentColor = new Color(0.2f, 0.6f, 1f),
                buttonColor = new Color(0.9f, 0.9f, 0.9f),
                buttonTextColor = Color.black,
                inputFieldColor = Color.white,
                inputFieldTextColor = Color.black,
                panelColor = Color.white,
                borderColor = new Color(0.7f, 0.7f, 0.7f)
            };

            // 暗色主题
            var darkTheme = new ThemeData
            {
                name = "Dark",
                type = ThemeType.Dark,
                primaryColor = new Color(0.2f, 0.2f, 0.2f),
                secondaryColor = new Color(0.3f, 0.3f, 0.3f),
                backgroundColor = new Color(0.15f, 0.15f, 0.15f),
                textColor = Color.white,
                accentColor = new Color(0.3f, 0.7f, 1f),
                buttonColor = new Color(0.3f, 0.3f, 0.3f),
                buttonTextColor = Color.white,
                inputFieldColor = new Color(0.2f, 0.2f, 0.2f),
                inputFieldTextColor = Color.white,
                panelColor = new Color(0.25f, 0.25f, 0.25f),
                borderColor = new Color(0.5f, 0.5f, 0.5f)
            };

            availableThemes.Add(lightTheme);
            availableThemes.Add(darkTheme);
        }

        /// <summary>
        /// 初始化UI
        /// </summary>
        private void InitializeUI()
        {
            // 切换主题按钮
            if (themeToggleButton != null)
            {
                themeToggleButton.onClick.AddListener(SwitchToNextTheme);
            }

            // 主题选择下拉菜单
            if (themeDropdown != null)
            {
                UpdateThemeDropdown();
                themeDropdown.onValueChanged.AddListener(OnThemeDropdownChanged);
            }
        }

        /// <summary>
        /// 缓存组件
        /// </summary>
        private void CacheComponents()
        {
            componentCache.Clear();

            foreach (var element in themedElements)
            {
                CacheComponent(element);
            }
        }

        /// <summary>
        /// 缓存单个元素的组件
        /// </summary>
        private void CacheComponent(GameObject element)
        {
            if (element == null) return;

            var components = element.GetComponents<Component>();
            componentCache[element] = components;
        }

        /// <summary>
        /// 启动主题过渡
        /// </summary>
        private void StartThemeTransition(ThemeData newTheme)
        {
            if (transitionCoroutine != null)
            {
                StopCoroutine(transitionCoroutine);
            }

            transitionCoroutine = StartCoroutine(ThemeTransitionCoroutine(newTheme));
        }

        /// <summary>
        /// 主题过渡协程
        /// </summary>
        private IEnumerator ThemeTransitionCoroutine(ThemeData newTheme)
        {
            LogDebug($"开始主题过渡: {currentTheme.name} -> {newTheme.name}");

            float startTime = Time.time;
            ThemeData startTheme = currentTheme;

            while (Time.time - startTime < transitionDuration)
            {
                float progress = (Time.time - startTime) / transitionDuration;
                progress = Mathf.SmoothStep(0f, 1f, progress);

                // 创建插值主题
                var interpolatedTheme = InterpolateThemes(startTheme, newTheme, progress);
                ApplyTheme(interpolatedTheme, false);

                yield return null;
            }

            // 确保最终主题正确应用
            ApplyTheme(newTheme, false);

            transitionCoroutine = null;
            LogDebug($"主题过渡完成: {newTheme.name}");
        }

        /// <summary>
        /// 插值两个主题
        /// </summary>
        private ThemeData InterpolateThemes(ThemeData theme1, ThemeData theme2, float progress)
        {
            var interpolated = new ThemeData
            {
                name = "Interpolated",
                type = progress < 0.5f ? theme1.type : theme2.type,
                primaryColor = Color.Lerp(theme1.primaryColor, theme2.primaryColor, progress),
                secondaryColor = Color.Lerp(theme1.secondaryColor, theme2.secondaryColor, progress),
                backgroundColor = Color.Lerp(theme1.backgroundColor, theme2.backgroundColor, progress),
                textColor = Color.Lerp(theme1.textColor, theme2.textColor, progress),
                accentColor = Color.Lerp(theme1.accentColor, theme2.accentColor, progress),
                buttonColor = Color.Lerp(theme1.buttonColor, theme2.buttonColor, progress),
                buttonTextColor = Color.Lerp(theme1.buttonTextColor, theme2.buttonTextColor, progress),
                inputFieldColor = Color.Lerp(theme1.inputFieldColor, theme2.inputFieldColor, progress),
                inputFieldTextColor = Color.Lerp(theme1.inputFieldTextColor, theme2.inputFieldTextColor, progress),
                panelColor = Color.Lerp(theme1.panelColor, theme2.panelColor, progress),
                borderColor = Color.Lerp(theme1.borderColor, theme2.borderColor, progress),
                shadowColor = Color.Lerp(theme1.shadowColor, theme2.shadowColor, progress),
                errorColor = Color.Lerp(theme1.errorColor, theme2.errorColor, progress),
                warningColor = Color.Lerp(theme1.warningColor, theme2.warningColor, progress),
                successColor = Color.Lerp(theme1.successColor, theme2.successColor, progress),
                fontSize = Mathf.RoundToInt(Mathf.Lerp(theme1.fontSize, theme2.fontSize, progress)),
                borderWidth = Mathf.Lerp(theme1.borderWidth, theme2.borderWidth, progress),
                cornerRadius = Mathf.Lerp(theme1.cornerRadius, theme2.cornerRadius, progress),
                shadowDistance = Mathf.Lerp(theme1.shadowDistance, theme2.shadowDistance, progress),
                backgroundImage = progress < 0.5f ? theme1.backgroundImage : theme2.backgroundImage,
                buttonImage = progress < 0.5f ? theme1.buttonImage : theme2.buttonImage,
                panelImage = progress < 0.5f ? theme1.panelImage : theme2.panelImage,
                primaryFont = progress < 0.5f ? theme1.primaryFont : theme2.primaryFont,
                secondaryFont = progress < 0.5f ? theme1.secondaryFont : theme2.secondaryFont,
                enableAnimations = progress < 0.5f ? theme1.enableAnimations : theme2.enableAnimations,
                animationSpeed = Mathf.Lerp(theme1.animationSpeed, theme2.animationSpeed, progress)
            };

            return interpolated;
        }

        /// <summary>
        /// 应用主题
        /// </summary>
        private void ApplyTheme(ThemeData theme, bool saveTheme)
        {
            if (theme == null) return;

            foreach (var element in themedElements)
            {
                ApplyThemeToElement(element, theme);
            }

            currentTheme = theme;

            // 更新当前主题索引
            for (int i = 0; i < availableThemes.Count; i++)
            {
                if (availableThemes[i] == theme)
                {
                    currentThemeIndex = i;
                    break;
                }
            }

            // 更新下拉菜单
            UpdateThemeDropdownSelection();

            if (saveTheme)
            {
                SaveCurrentTheme();
            }

            OnThemeChanged?.Invoke(theme);
            LogDebug($"已应用主题: {theme.name}");
        }

        /// <summary>
        /// 应用主题到元素
        /// </summary>
        private void ApplyThemeToElement(GameObject element, ThemeData theme)
        {
            if (element == null || !componentCache.ContainsKey(element))
                return;

            var components = componentCache[element];

            foreach (var component in components)
            {
                if (component is Image image)
                {
                    ApplyThemeToImage(image, theme);
                }
                else if (component is Text text)
                {
                    ApplyThemeToText(text, theme);
                }
                else if (component is Button button)
                {
                    ApplyThemeToButton(button, theme);
                }
                else if (component is InputField inputField)
                {
                    ApplyThemeToInputField(inputField, theme);
                }
                else if (component is Dropdown dropdown)
                {
                    ApplyThemeToDropdown(dropdown, theme);
                }
                else if (component is Toggle toggle)
                {
                    ApplyThemeToToggle(toggle, theme);
                }
                else if (component is Slider slider)
                {
                    ApplyThemeToSlider(slider, theme);
                }
                else if (component is Scrollbar scrollbar)
                {
                    ApplyThemeToScrollbar(scrollbar, theme);
                }
            }
        }

        /// <summary>
        /// 应用主题到Image组件
        /// </summary>
        private void ApplyThemeToImage(Image image, ThemeData theme)
        {
            var imageType = image.type;

            if (imageType == Image.Type.Sliced || imageType == Image.Type.Tiled)
            {
                // 背景图片
                if (image.transform.parent == image.transform.root ||
                    image.name.Contains("Background") ||
                    image.name.Contains("Panel"))
                {
                    image.color = theme.panelColor;
                }
                // 按钮图片
                else if (image.name.Contains("Button"))
                {
                    image.color = theme.buttonColor;
                }
                // 其他图片
                else
                {
                    image.color = theme.primaryColor;
                }
            }
            else
            {
                image.color = theme.primaryColor;
            }
        }

        /// <summary>
        /// 应用主题到Text组件
        /// </summary>
        private void ApplyThemeToText(Text text, ThemeData theme)
        {
            text.color = theme.textColor;

            if (theme.primaryFont != null)
            {
                text.font = theme.primaryFont;
            }

            if (text.fontSize != theme.fontSize)
            {
                text.fontSize = theme.fontSize;
            }
        }

        /// <summary>
        /// 应用主题到Button组件
        /// </summary>
        private void ApplyThemeToButton(Button button, ThemeData theme)
        {
            // 按钮背景
            var buttonImage = button.GetComponent<Image>();
            if (buttonImage != null)
            {
                buttonImage.color = theme.buttonColor;
            }

            // 按钮文本
            var buttonText = button.GetComponentInChildren<Text>();
            if (buttonText != null)
            {
                buttonText.color = theme.buttonTextColor;
            }

            // 按钮状态颜色
            var colors = button.colors;
            colors.normalColor = theme.buttonColor;
            colors.highlightedColor = Color.Lerp(theme.buttonColor, theme.accentColor, 0.3f);
            colors.pressedColor = Color.Lerp(theme.buttonColor, theme.accentColor, 0.5f);
            colors.disabledColor = Color.Lerp(theme.buttonColor, Color.gray, 0.5f);
            button.colors = colors;
        }

        /// <summary>
        /// 应用主题到InputField组件
        /// </summary>
        private void ApplyThemeToInputField(InputField inputField, ThemeData theme)
        {
            // 输入框背景
            var inputImage = inputField.GetComponent<Image>();
            if (inputImage != null)
            {
                inputImage.color = theme.inputFieldColor;
            }

            // 输入框文本
            inputField.textComponent.color = theme.inputFieldTextColor;
            inputField.placeholder.color = new Color(theme.inputFieldTextColor.r, theme.inputFieldTextColor.g, theme.inputFieldTextColor.b, 0.5f);

            // 输入框状态颜色
            var colors = inputField.colors;
            colors.normalColor = theme.inputFieldColor;
            colors.highlightedColor = Color.Lerp(theme.inputFieldColor, theme.accentColor, 0.3f);
            colors.pressedColor = Color.Lerp(theme.inputFieldColor, theme.accentColor, 0.5f);
            colors.disabledColor = Color.Lerp(theme.inputFieldColor, Color.gray, 0.5f);
            inputField.colors = colors;
        }

        /// <summary>
        /// 应用主题到Dropdown组件
        /// </summary>
        private void ApplyThemeToDropdown(Dropdown dropdown, ThemeData theme)
        {
            // 下拉菜单背景
            var dropdownImage = dropdown.GetComponent<Image>();
            if (dropdownImage != null)
            {
                dropdownImage.color = theme.inputFieldColor;
            }

            // 下拉菜单文本
            var dropdownText = dropdown.captionText;
            if (dropdownText != null)
            {
                dropdownText.color = theme.inputFieldTextColor;
            }

            // 下拉菜单项模板
            if (dropdown.template != null)
            {
                var templateImage = dropdown.template.GetComponent<Image>();
                if (templateImage != null)
                {
                    templateImage.color = theme.panelColor;
                }

                // 应用主题到所有下拉菜单项
                var itemTexts = dropdown.template.GetComponentsInChildren<Text>();
                foreach (var itemText in itemTexts)
                {
                    itemText.color = theme.textColor;
                }

                var itemImages = dropdown.template.GetComponentsInChildren<Image>();
                foreach (var itemImage in itemImages)
                {
                    if (itemImage != templateImage)
                    {
                        itemImage.color = theme.secondaryColor;
                    }
                }
            }
        }

        /// <summary>
        /// 应用主题到Toggle组件
        /// </summary>
        private void ApplyThemeToToggle(Toggle toggle, ThemeData theme)
        {
            // Toggle背景
            var toggleImage = toggle.GetComponent<Image>();
            if (toggleImage != null)
            {
                toggleImage.color = theme.inputFieldColor;
            }

            // Toggle文本
            var toggleText = toggle.GetComponentInChildren<Text>();
            if (toggleText != null)
            {
                toggleText.color = theme.textColor;
            }

            // Toggle状态颜色
            var colors = toggle.colors;
            colors.normalColor = theme.inputFieldColor;
            colors.highlightedColor = Color.Lerp(theme.inputFieldColor, theme.accentColor, 0.3f);
            colors.pressedColor = Color.Lerp(theme.inputFieldColor, theme.accentColor, 0.5f);
            colors.disabledColor = Color.Lerp(theme.inputFieldColor, Color.gray, 0.5f);
            toggle.colors = colors;

            // Checkmark
            if (toggle.graphic != null && toggle.graphic is Image checkmark)
            {
                checkmark.color = theme.accentColor;
            }
        }

        /// <summary>
        /// 应用主题到Slider组件
        /// </summary>
        private void ApplyThemeToSlider(Slider slider, ThemeData theme)
        {
            // 滑块背景
            var sliderImage = slider.GetComponent<Image>();
            if (sliderImage != null)
            {
                sliderImage.color = theme.secondaryColor;
            }

            // 填充区域
            if (slider.fillRect != null)
            {
                var fillImage = slider.fillRect.GetComponent<Image>();
                if (fillImage != null)
                {
                    fillImage.color = theme.accentColor;
                }
            }

            // 滑块手柄
            if (slider.handleRect != null)
            {
                var handleImage = slider.handleRect.GetComponent<Image>();
                if (handleImage != null)
                {
                    handleImage.color = theme.buttonColor;
                }
            }
        }

        /// <summary>
        /// 应用主题到Scrollbar组件
        /// </summary>
        private void ApplyThemeToScrollbar(Scrollbar scrollbar, ThemeData theme)
        {
            // 滚动条背景
            var scrollbarImage = scrollbar.GetComponent<Image>();
            if (scrollbarImage != null)
            {
                scrollbarImage.color = theme.secondaryColor;
            }

            // 滑块
            if (scrollbar.handleRect != null)
            {
                var handleImage = scrollbar.handleRect.GetComponent<Image>();
                if (handleImage != null)
                {
                    handleImage.color = theme.buttonColor;
                }
            }
        }

        /// <summary>
        /// 根据类型获取主题
        /// </summary>
        private ThemeData GetThemeByType(ThemeType type)
        {
            foreach (var theme in availableThemes)
            {
                if (theme.type == type)
                {
                    return theme;
                }
            }
            return null;
        }

        /// <summary>
        /// 加载保存的主题
        /// </summary>
        private void LoadSavedTheme()
        {
            if (PlayerPrefs.HasKey(SavedThemeKey))
            {
                string savedThemeName = PlayerPrefs.GetString(SavedThemeKey);
                var savedTheme = GetTheme(savedThemeName);

                if (savedTheme != null)
                {
                    currentTheme = savedTheme;
                    for (int i = 0; i < availableThemes.Count; i++)
                    {
                        if (availableThemes[i] == savedTheme)
                        {
                            currentThemeIndex = i;
                            break;
                        }
                    }
                    LogDebug($"已加载保存的主题: {savedThemeName}");
                }
                else
                {
                    LogWarning($"保存的主题 '{savedThemeName}' 不存在，使用默认主题");
                }
            }
        }

        /// <summary>
        /// 更新主题下拉菜单
        /// </summary>
        private void UpdateThemeDropdown()
        {
            if (themeDropdown == null) return;

            var options = new List<Dropdown.OptionData>();
            foreach (var theme in availableThemes)
            {
                options.Add(new Dropdown.OptionData(theme.name));
            }

            themeDropdown.options = options;
            UpdateThemeDropdownSelection();
        }

        /// <summary>
        /// 更新主题下拉菜单选择
        /// </summary>
        private void UpdateThemeDropdownSelection()
        {
            if (themeDropdown == null || currentTheme == null) return;

            for (int i = 0; i < availableThemes.Count; i++)
            {
                if (availableThemes[i] == currentTheme)
                {
                    themeDropdown.value = i;
                    break;
                }
            }
        }

        /// <summary>
        /// 主题下拉菜单改变回调
        /// </summary>
        private void OnThemeDropdownChanged(int index)
        {
            if (index >= 0 && index < availableThemes.Count)
            {
                SwitchToTheme(availableThemes[index]);
            }
        }

        /// <summary>
        /// 清理协程
        /// </summary>
        private void CleanupCoroutines()
        {
            if (transitionCoroutine != null)
            {
                StopCoroutine(transitionCoroutine);
                transitionCoroutine = null;
            }
        }

        #endregion

        #region Debug Methods

        /// <summary>
        /// 调试日志
        /// </summary>
        private void LogDebug(string message)
        {
            if (enableDebugLogs)
                Debug.Log($"[UIThemeSystem] {message}");
        }

        /// <summary>
        /// 警告日志
        /// </summary>
        private void LogWarning(string message)
        {
            if (enableDebugLogs)
                Debug.LogWarning($"[UIThemeSystem] {message}");
        }

        /// <summary>
        /// 错误日志
        /// </summary>
        private void LogError(string message)
        {
            if (enableDebugLogs)
                Debug.LogError($"[UIThemeSystem] {message}");
        }

        #endregion

        #region Public Properties

        /// <summary>
        /// 当前主题
        /// </summary>
        public ThemeData CurrentTheme => currentTheme;

        /// <summary>
        /// 当前主题索引
        /// </summary>
        public int CurrentThemeIndex => currentThemeIndex;

        /// <summary>
        /// 是否启用过渡动画
        /// </summary>
        public bool EnableTransitionAnimation
        {
            get => enableTransitionAnimation;
            set => enableTransitionAnimation = value;
        }

        /// <summary>
        /// 过渡时间
        /// </summary>
        public float TransitionDuration
        {
            get => transitionDuration;
            set => transitionDuration = Mathf.Max(0.1f, value);
        }

        #endregion
    }
}
